<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/common.css">
    <style>
        div#student > label {
            display: block;
            padding: 10px
        }

        #questions ul.options {
            display: flex;
            flex-direction: column;
            flex-wrap: wrap;
        }

        #questions ul.options > li {
            line-height: 1.5rem;
        }

        #questions li input {
            border: none;
            border-bottom: 1px solid #000;
            outline: none;
            padding: 5px;
            width: 5rem;
        }
        #questions li div {
            color: red;
            display: inline-block;
        }
        #questions li {
            list-style-type: none;
            display: inline-block;
            padding: 4px 10px;
            min-width: 30%;
        }


        #questions > ul > p > p {
            text-indent: 2em;
        }
    </style>
    <script type="application/javascript">
        let sequence = 1;
        let questionPosition = 1;
        let questions = [];
        let questionsId = [];
        let doneQuestion = [];

        function loadExam() {
            if (document.getElementById("name").value === "" || document.getElementById("code").value === "" || document.getElementById("scoreFourDegree").value === "") {
                alert("Please input the basic information of you");
                return;
            }
            let student = {code:document.getElementById("code").value,
                name:document.getElementById("name").value,
                scoreFourDegree:document.getElementById("scoreFourDegree").value
            };
            fetch("/student/update",{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(student)
            }).then(function (response){
                return response.json();
            }).then(function (data){
                console.log(data);
            });
            fetch("/exam/fetch?score=12&user=" + document.getElementById("code").value).then(function (response) {
                return response.json()
            }).then(function (data) {
                document.getElementById("showScore").style.display = "inline-block";
                document.getElementById("next").style.display = "inline-block";
                questions = data;
                getData(data[0]);
                questionPosition = 1;
                // for (const datum of data) {
                //     getData(datum);
                // }
                document.getElementById("name").disabled = true;
                document.getElementById("student").style.display = "none";
            })
        }

        function getData(questionId) {
            fetch("/exam/question?id=" + questionId).then(function (response) {
                return response.json()
            }).then(function (data) {
                show(data);
            })
        }
        function clearPreviousQuestion(){
            document.getElementById("questions").innerHTML="";
        }
        function show(question) {
            clearPreviousQuestion();
            let block = document.getElementById("questions");
            let questionItem = document.createElement("ul");
            block.append(questionItem);
            let content = document.createElement("p");
            //content.textContent = question.content;
            console.log(question.content);
            content.innerHTML = question.content;
            questionItem.append(content);
            let optional = document.createElement("div");
            questionItem.append(optional);
            if (question.options && question.options.length > 0) {
                questionsId.push(question.questionId);
            }
            for (let n in question.options) {
                let option = question.options[n];
                let item = document.createElement("li");
                optional.append(item);
                item.textContent = option.content;
                let checkbox = document.createElement("input");
                checkbox.setAttribute("type", "checkbox");
                checkbox.dataset.optionalId = option.optionalId;
                checkbox.dataset.remark = option.remark;
                item.append(checkbox);
            }
            let innerSequence = 1;
            for (let n in question.subQuestions) {
                let item = question.subQuestions[n];
                let li = document.createElement("li");
                li.textContent = "" + (innerSequence++);
                let input = document.createElement("input");
                input.dataset.remark1 = item.remark1;
                input.dataset.remark2 = item.remark2;
                input.dataset.remark3 = item.remark3;
                input.dataset.subQuestionId = item.subQuestionId;
                input.dataset.answer = item.answer;
                questionsId.push(item.subQuestionId);
                input.onblur = function () {
                    commitAnswer(input);
                }
                li.append(input);
                optional.append(li);
            }
        }

        function commitAnswer(input) {
            if (input.value === "")
                return;
            fetch("/exam/answer?user=" + document.getElementById("code").value + "&answer=" + input.value + "&subQuestionId=" + input.dataset.subQuestionId).then(function (response) {
                return response.json()
            }).then(function (data) {
                if (data.result === "correct") {
                    input.disabled = true;
                    doneQuestion.push(input.dataset.subQuestionId);
                    console.log("done2:" + input.dataset.subQuestionId)
                } else {
                    if (input.dataset.sequence) {
                        if (input.dataset.sequence === "4") {
                            alert("error");
                            input.disabled = true;
                            let notice = document.createElement("div");
                            notice.textContent=input.dataset.answer
                            input.parentNode.append(notice);
                            doneQuestion.push(input.dataset.subQuestionId);
                        } else {
                            alert(input.dataset["remark" + input.dataset.sequence]);
                            input.dataset.sequence = "" + (parseInt(input.dataset.sequence) + 1);
                        }
                    } else {
                        alert(input.dataset.remark1);
                        input.dataset.sequence = "2";
                    }
                    // let tip = input.nextElementSibling;
                    // if (tip != null)
                    //     tip.remove();
                    // tip = document.createElement("span");
                    // if (input.dataset.sequence) {
                    //     if (input.dataset.sequence == 4) {
                    //         tip.textContent = "error";
                    //         input.disabled = true;
                    //         doneQuestion.push(input.dataset.subQuestionId);
                    //     } else {
                    //         tip.textContent = input.dataset["remark" + input.dataset.sequence];
                    //         input.dataset.sequence = "" + (parseInt(input.dataset.sequence) + 1);
                    //     }
                    // } else {
                    //     tip.textContent = input.dataset.remark1;
                    //     input.dataset.sequence = 2;
                    // }
                    // input.parentElement.append(tip);
                }
            })
        }

        function showResult(showAll) {
            if (showAll && doneQuestion.length != questionsId.length) {
                alert("Please answer all question.")
                return;
            }
            let url = "/exam/result?user=" + document.getElementById("code").value;
            if(!showAll)
                url += "&questionId ="+questions[questionPosition];
            fetch(url).then(function (response) {
                return response.json()
            }).then(function (data) {
                document.getElementById("result").style.display = "block";
                document.getElementById("score").textContent = data.score;
                document.getElementById("lpsScore").textContent = data.lpsScore;
                document.getElementById("totalScore").textContent = data.totalScore;
            });
        }

        function answer() {
            let items = document.getElementById("question").querySelectorAll("input");
            let optionalId = -1;
            for (let i = 0; i < items.length; i++) {
                let item = items[i];
                if (item.checked) {
                    optionalId = item.dataset.optionalId;
                }
            }
            if (optionalId === -1)
                return;
            fetch("/exam/answer?user=" + document.getElementById("code").value + "&sequence=" + sequence++ + "&optionalId=" + optionalId).then(function (response) {
                return response.json()
            }).then(function (data) {
                if (data.result === "correct") {
                    next();
                } else {
                    for (let i = 0; i < items.length; i++) {
                        if (items[i].checked) {
                            items[i].disabled = true;
                            items[i].checked = false;
                        }
                    }
                }
            })
        }

        function checkScore(chk) {
            let element = document.getElementById("scoreFourDegree");
            if (chk.checked) {
                element.value = "-1";
                element.style.display = "none";
            } else {
                element.style.display = "inline";
            }
        }

        /**
         * show next question
         */
        function next(){
            if(questionPosition == questions.length)
            {
                showResult(true);
                return;
            }
            document.getElementById("result").style.display="none";
            getData(questions[questionPosition]);
            questionPosition ++;
        }
    </script>
</head>
<body>
<div id="student">
    <label>姓&nbsp;&nbsp;&nbsp;&nbsp;名: <input id="name" type="text"></label>
    <label>学&nbsp;&nbsp;&nbsp;&nbsp;号: <input id="code" type="text"></label>
    <label>四级分数: <input id="scoreFourDegree" type="text"></label>
    <label><input type="checkbox" onclick="checkScore(this)">未通过</label>
    <button onclick="loadExam()" class="button primary">get exam</button>
</div>

<div id="questions">
</div>
<button id="showScore" onclick="showResult(false)" style="display: none" class="button primary">show current score</button>
<button id="next" onclick="next()" style="display: none" class="button primary">next question/show total score</button>
<p style="display: none" id="result">
    Score: <span id="score"></span>
    LpsScore: <span id="lpsScore"></span>
    TotalScore: <span id="totalScore"></span>
</p>
</body>
</html>